﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CRMSimple.LogService.Configuration;
using System.IO;

namespace CRMSimple.LogService.Configuration.FileConfiguration
{
    public abstract class FileConfigurationRoot:ConfigurationRoot
    {
        /// <summary>
        /// 程序根路径
        /// </summary>
        public string BasePath
        {
            get { return AppDomain.CurrentDomain.BaseDirectory; }
        }
        /// <summary>
        /// json文件所在相对路径
        /// </summary>
        public string Path
        {
            get;
            set;
        }
        /// <summary>
        /// 加载配置文件
        /// </summary>
        public override void Load()
        {
            //加入缓存的设置
            using (var Stream = this.CreateReadStream())
            {
                try
                {
                    Load(this.StreamToString(Stream));
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally {
                    Stream.Dispose();
                }
            }
        }
        /// <summary>
        /// 创建读取或者写入的流
        /// </summary>
        protected abstract Stream CreateReadStream();
        /// <summary>
        /// 定义加载配置文件方式
        /// </summary>
        protected abstract void Load(string data);
        /// <summary>
        /// 写入配置文件
        /// </summary>
        public override void Write()
        {
            using (var Stream = this.CreateWirteStream())
            {
                try
                {
                    if (Stream.CanWrite)
                    {
                        var bytes = GetWriteBytes();
                        Stream.Write(bytes,0,bytes.Length) ;
                    }
                   
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
        /// <summary>
        /// 定义写入配置文件方式
        /// </summary>
        protected abstract byte[] GetWriteBytes();
        /// <summary>
        /// 创建读取或者写入的流
        /// </summary>
        protected abstract Stream CreateWirteStream();
    }
}
